<script setup lang="ts">
import { onMounted, ref, watch, computed } from 'vue';
import { useKnowledgeStore } from '@/store/kg/knowledge';

const props = defineProps({
  componentId: {
    type: String,
    required: true,
  },
  knowledgeList: {
    type: Array,
    default: () => []
  }
});

// 知识点store
const knowledgeStore = useKnowledgeStore();
// 当前组件已关联的知识点列表
const componentKnowledge = ref(props.knowledgeList || []);
// 已选择的知识点ID列表
const selectedKnowledgeIds = ref<string[]>([]);
// 加载状态
const loading = ref(false);
// 树形数据加载状态
const loadingTreeData = ref(false);
// 搜索关键词
const searchKeyword = ref('');
// 树形数据结构
const treeData = ref<any[]>([]);
// 树形控件的选中项
const selectedKeys = ref<string[]>([]);
// 树形控件的默认展开项
const defaultExpandedKeys = ref<string[]>([]);
// 树形控件引用
const treeRef = ref();

// 根据关键词过滤树数据
const filteredTreeData = computed(() => {
  if (!searchKeyword.value) {
    return treeData.value;
  }
  
  const keyword = searchKeyword.value.toLowerCase();
  
  // 深拷贝树数据并过滤
  const filterNode = (data: any[]): any[] => {
    return data.filter(node => {
      // 如果是课程节点，检查其子节点
      if (node.children) {
        const filteredChildren = filterNode(node.children);
        // 如果有匹配的子节点，保留课程节点并更新其子节点
        if (filteredChildren.length > 0) {
          return Object.assign({}, node, { children: filteredChildren });
        }
        // 或者课程名称包含关键词
        return node.label.toLowerCase().includes(keyword);
      }
      // 如果是知识点节点，检查名称是否包含关键词
      return node.label.toLowerCase().includes(keyword);
    });
  };
  
  return filterNode(JSON.parse(JSON.stringify(treeData.value)));
});

// 难度级别文本映射
const levelTextMap = {
  1: '基础',
  2: '简单',
  3: '一般',
  4: '困难',
  5: '进阶'
};

// 难度级别对应的标签类型
const levelTypeMap = {
  1: 'info',
  2: 'success',
  3: 'warning',
  4: 'danger',
  5: 'primary'
};

// 加载知识点树形结构数据
const loadKnowledgeTreeData = async () => {
  loadingTreeData.value = true;
  
  try {
    // 先重置所有状态
    selectedKnowledgeIds.value = [];
    selectedKeys.value = [];
    treeData.value = [];
    defaultExpandedKeys.value = [];
    
    // 使用树形结构API获取知识点树
    const treeDataResult = await knowledgeStore.getKnowledgeTree();
    treeData.value = treeDataResult;
    
    // 如果有数据，默认展开第一个课程节点
    if (treeDataResult.length > 0) {
      defaultExpandedKeys.value = [treeDataResult[0].id];
    }

    // 初始化已关联知识点的ID列表
    if (props.knowledgeList && props.knowledgeList.length > 0) {
      selectedKnowledgeIds.value = props.knowledgeList.map((k: any) => String(k.nodeId));
      selectedKeys.value = [...selectedKnowledgeIds.value];
    }
  } finally {
    loadingTreeData.value = false;
  }
};

// 处理树节点选择变更
const handleTreeCheck = (checkedNodes: any, checkedInfo: any) => {
  // 使用getCheckedKeys获取所有被选中的节点key
  if (treeRef.value) {
    const allCheckedKeys = treeRef.value.getCheckedKeys();
    // 过滤掉课程节点，只保留知识点节点
    selectedKnowledgeIds.value = allCheckedKeys.filter((key: string) => !key.startsWith('course-'));
  }
};

// 在组件挂载时加载数据
onMounted(async () => {
  loading.value = true;
  await loadKnowledgeTreeData();
  loading.value = false;
});

// 当组件ID变化时重新加载数据
watch(() => props.componentId, async (newVal, oldVal) => {
  if (newVal !== oldVal) {
    loading.value = true;
    // 重置状态
    selectedKnowledgeIds.value = [];
    selectedKeys.value = [];
    componentKnowledge.value = [];
    await loadKnowledgeTreeData();
    loading.value = false;
  }
});

// 当知识点列表变化时更新选中状态
watch(() => props.knowledgeList, (newVal) => {
  // 重置之前的状态
  selectedKnowledgeIds.value = [];
  selectedKeys.value = [];
  componentKnowledge.value = [];
  
  if (newVal && newVal.length > 0) {
    componentKnowledge.value = newVal;
    selectedKnowledgeIds.value = newVal.map((k: any) => String(k.nodeId));
    selectedKeys.value = [...selectedKnowledgeIds.value];
  }
}, { deep: true });

// 暴露分配数据给父组件
defineExpose({
  selectedKnowledgeIds,
});
</script>

<template>
  <div v-loading="loading">
    <h4 class="mb-4">为组件关联知识点</h4>
    
    <!-- 搜索框 -->
    <div class="search-container mb-4">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索知识点..."
        :prefix-icon="'Search'"
        clearable
      />
    </div>
    
    <!-- 树形选择器 -->
    <div class="tree-container">
      <el-tree
        ref="treeRef"
        :data="filteredTreeData"
        show-checkbox
        node-key="id"
        :check-strictly="false"
        :default-expanded-keys="defaultExpandedKeys"
        :default-checked-keys="selectedKeys"
        :props="{ children: 'children', label: 'label' }"
        @check="handleTreeCheck"
      >
        <template #default="treeNode">
          <div v-if="treeNode.data.id.startsWith('course-')" class="course-node">
            <i class="el-icon-folder-opened mr-1"></i>
            <span class="course-name">{{ treeNode.data.label }}</span>
            <span class="course-count">({{ treeNode.data.children?.length || 0 }}个知识点)</span>
          </div>
          <div v-else class="knowledge-node">
            <span class="knowledge-name">{{ treeNode.data.label }}</span>
            <el-tag 
              v-if="treeNode.data.level"
              size="small" 
              :type="levelTypeMap[treeNode.data.level] || 'info'" 
              class="ml-2"
            >
              {{ levelTextMap[treeNode.data.level] || treeNode.data.level }}
            </el-tag>
          </div>
        </template>
      </el-tree>
    </div>

    <div class="mt-4 text-right">
      <span class="text-gray-500">共选择了 {{ selectedKnowledgeIds.length }} 个知识点</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.mb-4 {
  margin-bottom: 1rem;
}

.mt-4 {
  margin-top: 1rem;
}

.ml-2 {
  margin-left: 0.5rem;
}

.mr-1 {
  margin-right: 0.25rem;
}

.text-right {
  text-align: right;
}

.text-gray-500 {
  color: #909399;
}

.search-container {
  margin-bottom: 16px;
}

.tree-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.course-node {
  font-weight: bold;
  display: flex;
  align-items: center;
  
  .course-name {
    margin-right: 5px;
  }
  
  .course-count {
    color: #909399;
    font-size: 12px;
    font-weight: normal;
  }
}

.knowledge-node {
  display: flex;
  align-items: center;
  
  .knowledge-name {
    margin-right: 5px;
  }
}
</style> 